<?php

namespace Common\ModelSQ;

use Common\Lib\RedisHandle;

class ParkApi extends ModelSQBase
{
    public function request($p)
    {
        $config = C('PARK_API');
        $str = json_encode($p) . $config['signKey'];
        $sign = md5($str);

        $params = array(
            'cid' => $config['cid'],
            'tn' => $this->getToken(),
            'sn' => strtoupper($sign),
            'v' => $config['v'],
            'p' => json_encode($p)
        );

        $params = urldecode(http_build_query($params));
        elog($config['funcurl'] . '?' . urldecode($params));
        $result = http_request($config['funcurl'] . '?' . urldecode($params));
        $result = $result ? json_decode($result, 1) : null;
        return $result;
    }

    private function getToken()
    {
        $token = RedisHandle::$redis->get('ParkToken');
        if ($token) {
            return $token;
        }

        $config = C('PARK_API');
        $params = array(
            'cid' => $config['cid'],
            'usr' => $config['usr'],
            'psw' => $config['psw']
        );
        $params = urldecode(http_build_query($params));
        $result = http_request($config['loginurl'] . '?' . $params);
        $result = $result ? json_decode($result, 1) : null;
        if ($result && $result['resultCode'] === 0) {
            $token = $result['token'];
            RedisHandle::$redis->set('ParkToken', $token, 6000); //服务器有效2小时，这里存1小时40分钟
            return $token;
        }
        elog('停车场接口获取TOKEN失败');
        elog($result);
    }
}